package com.cn.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.cn.pojo.TypeInfo;
import com.cn.pojo.UserInfo;
import com.cn.service.TypeService;
import com.cn.service.UserService;

@Controller
public class UserController {
	@Autowired
	@Qualifier("userService")
	UserService userService;
	@Autowired
	@Qualifier("typeService")
	TypeService typeService;
	@RequestMapping(value="/login")
	public ModelAndView login(String loginName,String passWord,HttpSession session,ModelAndView mv) {
		UserInfo user=userService.login(loginName, passWord);
		if(user!=null&&user.getGust()==1) {
			session.setAttribute("user", user);
			mv.setViewName("admin");
		}
		else if(user!=null&&user.getGust()==2) {
			session.setAttribute("user", user);
			mv.setViewName("user");
		}
		else {
			mv.addObject("message", "用户名或密码错误，请重新输入");
			mv.setViewName("loginForm");
		}
		return mv;
	}
	@RequestMapping(value="/register")
	public ModelAndView register(String loginName, String userName, String passWord, String phone, String email, String sex,
			Integer age, String qq, String address,ModelAndView mv) {
		String loginName1=userService.selectByloginName(loginName);
		if(loginName1!=null&&loginName1.equals(loginName)) {
			mv.addObject("message","该用户名已存在，请重新注册");
			mv.setViewName("registerForm");
		}
		else {
			boolean register=userService.register(loginName, userName, passWord, phone, email, sex, age, qq, address);
			mv.setViewName("loginForm");
		}
		return mv;
	}
	@RequestMapping(value="/exit")
	public ModelAndView exit(ModelAndView mv,HttpSession session,HttpServletRequest request) {
		session=request.getSession(false);
		UserInfo user=(UserInfo) session.getAttribute("user");
		if(session!=null&&user.getGust()==1) {
			session.invalidate();
			mv.setViewName("admin");
		}
		if(session!=null&&user.getGust()==2) {
			session.invalidate();
			mv.setViewName("user");
		}
		return mv;
	}
}
